import { readJson } from 'fs-extra';
import path from 'path';

import { addOhPackageDps, buildAppAndHapsAndCheckFile } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel, CURRENT_HMOS_API,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  sdkPathConvertMap,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: [ModuleTemplateType.SharedLibrary]
};

export const testFun: TestCaseFun = async (project, taskConfig, record) => {
  // 1. 获取本地 sdk的配置信息
  const sdkHome = process.env['DEVECO_SDK_HOME'];
  if (!sdkHome) {
    throw new Error('SDK Home env variable DEVECO_SDK_HOME doesn\'t exist');
  }
  const configPath = path.resolve(sdkHome, sdkPathConvertMap[CURRENT_HMOS_API] ?? '', 'hms/ets/uni-package.json');
  const uniPackageConfig = await readJson(configPath);

  // 2. 给entry模块添加远程hsp依赖
  const entryPath = project.getModule('entry').moduleRootPath();
  if ('MR1' === uniPackageConfig.releaseType) {
    await addOhPackageDps(entryPath, { 'hsp_api10_100': '1.0.0' });
  }

  // 3. 执行build haps 和 build app
  await buildAppAndHapsAndCheckFile(project, taskConfig, record);
};

TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_DevEco_Studio_Build_SkipSignHap_Stage_Linux_06(sign)')
  .description('06、用户目录\\.hvigor\\hvigor-config.json5配置enableSignTask，linux模拟流水线CI场景构建Hap、Hsp包(签名)')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).sign(SignType.Sign).build())
  .testFun(testFun)
  .load();

TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_DevEco_Studio_Build_SkipSignHap_Stage_Linux_06(no-sign)')
  .description('06、用户目录\\.hvigor\\hvigor-config.json5配置enableSignTask，linux模拟流水线CI场景构建Hap、Hsp包(不签名)')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).build())
  .testFun(testFun)
  .load();
